package com.dream.service.recommender.hub.rec;

import com.dream.common.model.response.BaseResponse;
import com.dream.common.model.response.ErrorCode;
import com.dream.service.recommender.hub.util.CacheUtil;
import com.dream.service.recommender.hub.util.ParamUtil;
import com.dream.service.recommender.toolkits.cache.RedisCache;
import com.dream.service.recommender.toolkits.utils.ConfigUtil;
import com.dream.service.recommender.toolkits.utils.StringUtils;
import com.dream.service.search.api.SearchRecallService;
import com.dream.service.search.domain.entity.ShopifyProductRecallResult;
import com.dream.service.search.domain.request.ShopifyProductSearchRequest;
import com.dream.service.recommender.base.impl.BaseRecommenderService;
import com.dream.service.recommender.domain.request.BaseRequest;
import com.dream.service.recommender.domain.request.FrontParam;
import com.dream.service.recommender.domain.response.RecommenderData;
import com.dream.service.recommender.domain.response.RecommenderItem;
import com.dream.service.recommender.domain.response.RecommenderShopifyProduct;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 * P.C. 坑位推荐
 * Created by zhiji on 2016/05/14.
 */
public class PPCListRecommender extends BaseRecommenderService {

    private SearchRecallService searchRecallService;

    public SearchRecallService getSearchRecallService() {
        return searchRecallService;
    }

    @Autowired
    public void setSearchRecallService(SearchRecallService searchRecallService) {
        this.searchRecallService = searchRecallService;
    }

    // 获取商品数据倍数
    private int multiple = 2;

    // 失效时间间隔 (sec)
    private int residue_time_interval = 5 * 60;

    // 缓存
    private final String cacheKey = "rec_ppc_list_";

    private final String shopify_url_prefix = ConfigUtil.getPro("shopify_url_prefix");

    // 缓存
    private RedisCache redisCache = RedisCache.getInstance();

    @Override
    public BaseResponse<RecommenderData> getRecommender(BaseRequest<FrontParam> frontParamBaseRequest) {
        long sTime = System.currentTimeMillis();
        BaseResponse<RecommenderData> recommenderResponse = new BaseResponse<RecommenderData>();
        try {
            if (frontParamBaseRequest == null || frontParamBaseRequest.getParam() == null || frontParamBaseRequest.getParam().getUser() == null) {
                return buildResult(recommenderResponse, false, ErrorCode.PARAM_ERROR.getCode(), ErrorCode.PARAM_ERROR.getError_msg(), null);
            }
            FrontParam frontParam = frontParamBaseRequest.getParam();
            int pagesize = ParamUtil.getPageSize(frontParam);
            int page = ParamUtil.getPage(frontParam);
            /*int skip = pagesize * (page - 1);*/
            String pin = ParamUtil.getPin(frontParam);
            String uuid = ParamUtil.getUUid(frontParam);
            // 获取已经展示的Key
            Set<Long> existKeys = gatherExistKeys(pin, uuid, page, pagesize);
//            System.out.println(existKeys.size());
            List<Long> needKeys = frontParam.getSpus();
            List<ShopifyProductRecallResult> recallResults = gatherSearchRecallData(pagesize * multiple, existKeys, needKeys, 0);

            RecommenderData recommenderData = buildResult(recallResults);
            recommenderResponse = buildResult(recommenderResponse, true, ErrorCode.OK.getCode(), "", recommenderData, 0, pagesize);
            Set<Long> keys = rebuildPositionInfo(recommenderResponse.getResult());
            backupExistKeys(pin, uuid, keys);
            long usedTime = System.currentTimeMillis() - sTime;
            recommenderData.setLatency(usedTime);
            recommenderResponse.setLatency(usedTime);
            return recommenderResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return buildResult(recommenderResponse, false, ErrorCode.PROCESS_ERROR.getCode(), e.getMessage(), null);
        }
    }

    /**
     * 更新位置信息
     * @param recommenderData
     * @return
     */
    public Set<Long> rebuildPositionInfo(RecommenderData recommenderData) {
        if (recommenderData == null || StringUtils.isEmpty(recommenderData.getList())) {
            return null;
        }
        List<RecommenderItem> items = recommenderData.getList();
        Set<Long> keys = new HashSet<Long>();
        int pos = 1;
        for (RecommenderItem recommenderItem : items) {
            recommenderItem.setPos(pos++);
            if (recommenderItem instanceof RecommenderShopifyProduct) {
                try {
                    keys.add(((RecommenderShopifyProduct) recommenderItem).getProduct_id());
                } catch (Exception e) {}
            }
        }
        return keys;
    }

    /**
     * 获取已存在的Keys
     * @param pin
     * @param uuid
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Set<Long> gatherExistKeys(String pin, String uuid, int pageNum, int pageSize) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) {
            return Collections.emptySet();
        }
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = cacheKey.concat("_").concat(major_uid);
        if (pageNum == 1) {
            redisCache.delKey(key.getBytes());
            return Collections.emptySet();
        }
        Set<Long> keys = CacheUtil.getExistSpus(redisCache, key, (pageNum - 1) * pageSize);
        if (keys == null) {
            return Collections.emptySet();
        }
        return keys;
    }

    private List<ShopifyProductRecallResult> gatherSearchRecallData(int limit, Set<Long> existKeys, List<Long> needKeys, int skip) {

        ShopifyProductSearchRequest request = new ShopifyProductSearchRequest();
        request.setLimit(limit);
        request.setSkip(skip);
        if (existKeys != null && !existKeys.isEmpty()) {
            request.setExistKeys(existKeys);
        }
        if (needKeys != null && !needKeys.isEmpty()) {
            request.setNeedKeys(needKeys);
        }
        try {
            if (searchRecallService == null) {
                return null;
            }
            BaseResponse<List<ShopifyProductRecallResult>> recallResponse = searchRecallService.shopifyProductSearchRecall(request);
            if (recallResponse.isSuccess()) {
                return recallResponse.getResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void backupExistKeys(String pin, String uuid, Set<Long> keys) {
        if (StringUtils.isEmpty(pin) && StringUtils.isEmpty(uuid)) return;
        String major_uid = StringUtils.isEmpty(pin) ? uuid : pin;
        String key = cacheKey.concat("_").concat(major_uid);
        CacheUtil.backupCache(redisCache, key, keys, residue_time_interval, -1);
    }

    /**
     * 封装结果
     * @param recallResults
     * @return
     */
    private RecommenderData buildResult(List<ShopifyProductRecallResult> recallResults) {
        if (StringUtils.isEmpty(recallResults)) {
            return new RecommenderData();
        }
        RecommenderData<RecommenderShopifyProduct> recommenderData = new RecommenderData<RecommenderShopifyProduct>();
        List<RecommenderShopifyProduct> recommenderShopifyProducts = new ArrayList<RecommenderShopifyProduct>();
        recommenderData.setList(recommenderShopifyProducts);
        for (ShopifyProductRecallResult recallResult : recallResults) {
            RecommenderShopifyProduct recommenderShopifyProduct = buildProduct(recallResult);
            if (recommenderShopifyProduct != null) {
                recommenderShopifyProducts.add(recommenderShopifyProduct);
            }
        }
        // 排序
        return recommenderData;
    }

    /**
     * 封装商品信息
     * @param recallResult
     * @return
     */
    private RecommenderShopifyProduct buildProduct(ShopifyProductRecallResult recallResult) {
        if (recallResult == null) {
            return null;
        }
        RecommenderShopifyProduct recommenderShopifyProduct = new RecommenderShopifyProduct();

        recommenderShopifyProduct.setTitle(recallResult.getTitle());
        recommenderShopifyProduct.setImage_url(recallResult.getImage_url());
        recommenderShopifyProduct.setProduct_id(recallResult.getProduct_id());
        recommenderShopifyProduct.setPrice(recallResult.getPrice());
        recommenderShopifyProduct.setOrig_price(recallResult.getOrig_price());
        if (!StringUtils.isEmpty(recallResult.getDisplay())) {
            recommenderShopifyProduct.setDisplay(recallResult.getDisplay());
        }
        if (!StringUtils.isEmpty(recallResult.getHandle())) {
            recommenderShopifyProduct.setSkip_url(shopify_url_prefix.concat(recallResult.getHandle()));
        }
        /*recommenderShopifyProduct.setPromotion_remain_time();*/
        return recommenderShopifyProduct;
    }
}
